package com.example.interview.no0107.solution;

import com.example.interview.no0107.Solution;

/**
 * @Description 解答-旋转矩阵
 * @ClassName SolutionImpl
 * @Author Administrator
 * @Date 2020/5/20 10:26
 * @Version 1.0.0
 */
public class SolutionImpl1 implements Solution {
    @Override
    public void rotate(int[][] matrix) {
        if (matrix.length < 2) {
            return;
        }

        // 将矩阵以左上到右下的对角线为中线，进行对称变换
        for (int row = 0; row < matrix.length; row++) {
            for (int col = row; col < matrix.length; col++) {
                exchange(matrix, row, col, col,row);
            }
        }

        // 将矩阵以纵向中线为中线，进行对称变换
        for (int col = 0; col < matrix.length / 2; col++) {
            for(int row = 0; row < matrix.length; row++) {
                exchange(matrix, row, col, row, matrix.length - 1 - col);
            }
        }
    }

    // 无需新增额外内存的交换方法
    private void exchange(int[][] matrix, int fromRow, int fromCol, int toRow, int toCol) {
        if (fromRow == toRow && fromCol == toCol) {
            return;
        }
        matrix[fromRow][fromCol] = matrix[fromRow][fromCol] + matrix[toRow][toCol];
        matrix[toRow][toCol] = matrix[fromRow][fromCol] - matrix[toRow][toCol];
        matrix[fromRow][fromCol] = matrix[fromRow][fromCol] - matrix[toRow][toCol];
    }
}
